package com.xuecheng.base.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EncryptUtil {

    private static final Logger logger = LoggerFactory.getLogger(EncryptUtil.class);

    /**
     * 将字节数组进行base64编码
     * @param bytes 字节数组
     * @return base64编码后的字符串
     */
    public static String encodeBase64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 将base64编码的字符串进行解码
     * @param str base64编码的字符串
     * @return 解码后的字节数组
     */
    public static byte[] decodeBase64(String str) {
        return Base64.getDecoder().decode(str);
    }

    /**
     * 将字符串进行utf-8编码后进行base64编码
     * @param str 字符串
     * @return base64编码后的字符串
     */
    public static String encodeUTF8StringBase64(String str) {
        return Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 将base64编码的字符串进行解码，并转换为utf-8编码的字符串
     * @param str base64编码的字符串
     * @return utf-8编码的字符串
     */
    public static String decodeUTF8StringBase64(String str) {
        byte[] bytes = Base64.getDecoder().decode(str);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    /**
     * url编码
     * @param url url
     * @return url编码后的字符串
     */
    public static String encodeURL(String url) {
        try {
            return URLEncoder.encode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.warn("URLEncode失败", e);
            return null;
        }
    }

    /**
     * url解码
     * @param url url
     * @return url解码后的字符串
     */
    public static String decodeURL(String url) {
        try {
            return URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.warn("URLDecode失败", e);
            return null;
        }
    }
}
